<template>
  <div id="comp-lookUserDialog">
    <el-dialog title="查看用户" :visible.sync="isDialog" width="30%">
      <div class="container">
        <el-row type="flex" justify="space-between">
          <el-col class="col-flex" :span="10">
            <el-input style="height: 28px" placeholder="请输入工号/姓名/职位" clearable v-model="search"></el-input>
            <el-button type="primary" @click="getUserDataList">搜索</el-button>
          </el-col>
          <el-col :span="2.5">
            <el-button @click="addUser" type="primary">绑定员工</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="tableData" height="452" style="width: 100%">
              <el-table-column header-align="left" prop="userCode" width="100" align="left" label="工号"> </el-table-column>
              <el-table-column header-align="left" prop="realName" width="100" align="left" label="姓名"> </el-table-column>
              <el-table-column header-align="left" prop="position" width="230" align="left" label="职位"> </el-table-column>
              <el-table-column header-align="left" width="100" align="left" label="操作">
                <template #default="scope">
                  <div v-if="scope.row.isAdmin !== 1" class="oper-cancel" @click="cancelAssociat(scope.row)">取消关联</div>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
      <el-dialog width="30%" title="选择用户" v-if="isSelectUser" :visible.sync="isSelectUser" append-to-body>
        <div class="block">
          <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        </div>
        <div class="box" style="height: 403px; overflow: auto">
          <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="['00000000-0000-0000-0000-000000000000']" :render-content="renderContent" highlight-current :filter-node-method="filterNode" :props="defaultProps"></el-tree>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="isSelectUser = false">取 消</el-button>
          <el-button @click="confirmSelect" type="primary">确 认</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapTreeAddIcon } from "@/util/util";
import { mapState } from "vuex";

export default {
  name: "lookUserDialog",
  props: {
    lookUserDialog: {
      type: Boolean,
    },
    roleid: {
      type: String,
    },
  },
  watch: {
    roleid: {
      handler() {
        this.getUserDataList();
      },
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    isSelectUser(val) {
      if (val) {
        this.getSubCompanyView();
      }
    },
  },
  computed: {
    isDialog: {
      get() {
        return this.lookUserDialog;
      },
      set(newVal) {
        if (!newVal) this.init();
        this.$emit("update:lookUserDialog", newVal);
      },
    },
    ...mapState({
      UserInfo: (state) => state.common.UserInfo,
      usersList: (state) => state.common.userList,
    }),
  },
  data() {
    return {
      filterText: "",

      search: "",
      tableData: [],
      isSelectUser: false, //选择用户弹窗
      defaultProps: {
        children: "childrens",
        label: "name",
      },
      treeData: [],
      defaultCheckedKeys: [],
    };
  },
  created() {},
  methods: {
    confirmSelect() {
      let handleAfterNode = this.getHigherCheckedNodes(this.$refs.tree.store);
      // handleAfterNode.forEach(item => {
      //   if (item.type == 0) item.id = this.UserInfo.companyId;
      // });
      // 仅人员
      handleAfterNode = this.getLowCheckedNodes();
      // roleid
      const ids = handleAfterNode.map((i) => i.primarykey);
      if (ids && ids.length > 0) {
        this.$api.systemManagement.BindCurrentRole({ ids, roleId: this.roleid }).then((res) => {
          if (res.data.status === 200) {
            this.getUserDataList();
            this.isSelectUser = false;
          }
        });
      } else {
        this.$message.warning("请至少选择一个员工进行绑定");
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <img width="15px" src={data.icons} />
          <span title={node.label} style="margin-left:5px;font-size: 12px;position: relative;top: -1px;">
            {node.label.length > 20 ? node.label.slice(0, 20) + "..." : node.label}
          </span>
        </span>
      );
    },
    addUser() {
      this.isSelectUser = true;
      // this.isDialog = false;
      // this.$router.push({ name: 'addUser', query: { type: 'isAddJump', roleid: this.roleid, randomNum: Math.floor(Math.random() * 900) + 100 } });
    },
    init() {
      this.search = "";
    },
    async getUserDataList() {
      const { data } = await this.$api.systemManagement.GetUserDataList({ roleId: this.roleid, keyWord: this.search });
      this.defaultCheckedKeys = data.data?.map((item) => item.userid);
      this.tableData = data.data;
    },
    async getSubCompanyView() {
      //公司部门子集人员树
      const { data } = await this.$api.publicApi.GetSubCompanyView();
      this.treeData = JSON.parse(JSON.stringify(mapTreeAddIcon(this.handleData([data.data]))));
      // this.updateDefaultCheckKeys();
    },
    treeDataGetUser(data) {
      // tree扁平化
      return data.reduce((p, c) => p.concat([c], this.treeDataGetUser(c.childrens || [])), []);
    },

    /** 获取最高层节点 */
    getHigherCheckedNodes(store) {
      const checkedNodes = [];
      const traverse = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data);
          }
          if (child.indeterminate) {
            traverse(child);
          }
        });
      };
      traverse(store);
      return checkedNodes;
    },

    getLowCheckedNodes() {
      let handleAfterNode = this.$refs.tree.getCheckedNodes();
      const userArr = handleAfterNode.filter((item) => item.type == 3);
      return userArr;
    },
    handleData(data, parentObj = {}) {
      // 关联父子数据  1   1-1   1-1-1    1-1-1-1   n-n-n-n
      data.map((item, index) => {
        if (item.isAdmin) {
          item.disabled = true;
        }
        if (parentObj.relatedId) {
          item.relatedId = parentObj.relatedId + `-${index + 1}`;
        } else {
          item.relatedId = index + 1 + "";
        }
        if (item.childrens && item.childrens.length) {
          this.handleData(item.childrens, item);
        }
      });
      return data;
    },

    /** 设置默认值 */
    updateDefaultCheckKeys(arr = this.selectedList) {
      this.defaultCheckedKeys = arr.map((item) => item.dataId || item.userId); //已选中员工
      const treeFlat = this.treeDataGetUser(this.treeData);
      const userAllCount = treeFlat.filter((i) => i.type === 3).length; //所有员工数
      if (userAllCount === this.defaultCheckedKeys.length) {
        this.defaultCheckedKeys = treeFlat.map((i) => i.id);
      }

      // console.log(this.isHide, this.defaultCheckedKeys)
      this.treeData = JSON.parse(JSON.stringify(this.usersList));
      if (this.isHide) {
        arr.forEach((item) => {
          this.getCompleteData(this.treeData, item.userId, true);
        });
      } else {
        arr.forEach((item) => {
          item.type = item.dataType;
          const { name = "" } = this.getCompleteData(this.treeData, item.dataId) || {};
          item.name = name;
        });
        // this.confirmSelect()
      }
    },

    /** 递归对应参数 */
    getCompleteData(arr, id, isDisabled) {
      const len = arr.length;
      let o = "";
      let parent = "";
      for (let i = 0; i < len; i++) {
        const item = arr[i];
        if (item.id == id) o = item;
        else if (item?.childrens?.length) {
          parent = item;
          o = this.getCompleteData(item.childrens, id, isDisabled);
        }
        if (o) {
          if (isDisabled) {
            o.disabled = true;
            const obj = parent?.childrens?.find((item) => !item.disabled);
            if (!obj && parent) parent.disabled = true;
            // console.log(o, parent)
          }
          return o;
        }
      }
    },

    cancelAssociat(row) {
      //取消关联
      const userId = row.userid;
      this.$confirm(`您将对${row.realName}执行取消关联的操作, 是否继续?`, "提示", {
        confirmButtonText: "取消关联",
        cancelButtonText: "返回",
        type: "warning",
      })
        .then(async () => {
          const { data } = await this.$api.systemManagement.CancelCurrentRole({ userId, uId: row.primarykey });
          if (data.status === 200) {
            this.$message({ type: "success", message: "取消关联 成功" });
          }
          this.getUserDataList();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
#comp-lookUserDialog {
  :deep(.el-dialog) {
    min-width: 570px;
    height: 565px;
  }
  :deep(.el-table th) {
    text-align: left !important;
  }
  :deep(.el-table th.el-table__cell) {
    background: #f7f8fc;
  }
  :deep(.col-flex) {
    display: flex;
  }
  :deep(.el-input__inner) {
    height: 28px;
  }
  :deep(.el-row) {
    margin-bottom: 20px;
  }
  .container {
    height: 500px;
    display: flex;
    flex-direction: column;
    .oper-cancel {
      text-decoration: underline;
      color: #5c90f8;
      cursor: pointer;
    }
  }
}
</style>
